package generic.gui.util;

import exceptions.PersistenceExceptionMessage;
import generic.form.GenericInOutFile;
import generic.interfaces.GenericImportFile;
import generic.interfaces.PersistInFile;

import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import user.interfaces.icones.PathIcons;

import load.properties.Mensagem;
import load.properties.Path;

@SuppressWarnings("rawtypes")
public class ImportEntity <ENTITY extends PersistInFile> extends GenericInOutFile {
	
	private ArrayList<ENTITY> entities;
	private GenericImportFile gImportFile;
	private ENTITY entity;
	private JProgressBarForm progress;
	
	public ImportEntity(String path, ENTITY entity, GenericImportFile imp, int time) {
		this(path, entity, imp);
		setTime(time);
	}
	public ImportEntity(String path, ENTITY entity, GenericImportFile imp) {
		setDialogTitle(Mensagem.getValue(Mensagem.TITULO_IMPORTAR_REGISTROS));
		setPath(path);
		setEntity(entity);
		setgImportFile(imp);
		if (getTime() == null)
			setTime(20);
	}
	
	public void loadInterface(String titulo) {
		JFileChooser chooser = new JFileChooser(Path.getValue(getPath()));
		chooser.setFileFilter(criarFiltroTxt());
		chooser.setDialogTitle(getDialogTitle());
		chooser.setVisible(true);
		chooser.showOpenDialog(null);
		
		if (chooser.getSelectedFile() != null) {
			setPathFile(chooser.getSelectedFile());
			final int sizeFile = getSizeFile();
			progress = new JProgressBarForm(titulo, "Importando o registro 0 de " +getSizeFile() +" no total.", 0, sizeFile);
			getProgress().setWorker(new SwingWorker(){
				
				@Override
				protected Object doInBackground() throws Exception {
					try {
						loadEntities();
						if (getEntities().size() == sizeFile)
							saveInBanco();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return getEntities();
				}
				@Override
				protected void done() {
					if (getEntities().size() != getSizeFile()) {
						JOptionPane.showMessageDialog(null, Mensagem.getValue(Mensagem.FISCAL_ERRO_LINHA_NCM) 
								+" " +(getEntities().size() + 1) +".",Mensagem.getValue(Mensagem.TITULO_DIALOGO_ALERTA), 
								JOptionPane.WARNING_MESSAGE);
						
					}
					progress.dispose();
					try {
						if (getEntity().findAll().size() == sizeFile)
							 JOptionPane.showMessageDialog(progress, "Arquivo importado com sucesso.", "Sucesso", JOptionPane.PLAIN_MESSAGE, new ImageIcon(getClass().getResource(PathIcons.ICO_APLICADO)));
					} catch (HeadlessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (PersistenceExceptionMessage e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					getgImportFile().finalLoadAndSave();
				}
				
			});
			getProgress().execute();
		}
	}
	
	@SuppressWarnings({ "unchecked", "static-access"})
	private void saveInBanco() throws InterruptedException, PersistenceExceptionMessage {
		getEntity().order(getEntities());
		
		//ArrayList<Entity> ent = getEntity().findAll();
		getEntity().removeAll();
		getProgress().setTitle(Mensagem.getValue(Mensagem.TITULO_GRAVAR_REGISTROS));
		getProgress().getLabel().setText("Gravando o registro 0 de " +getSizeFile() +" no total.");
		getProgress().getProgress().setValue(0);

		for (ENTITY entity2 : getEntities()) {
			entity2.persist();
			getProgress().getProgress().setValue(progress.getProgress().getValue() + 1);
			getProgress().getLabel().setText("Gravando o registro " +progress.getProgress().getValue() +" de " +getSizeFile() +" no total.");
			if (getTime() > 0)
				Thread.currentThread().sleep(getTime());
		}
	}
	
	@SuppressWarnings({ "unchecked", "resource", "static-access" })
	protected Object loadEntities() throws InterruptedException {
		try {
			FileReader arq = new FileReader(getPathFile());
		    BufferedReader lerArq = new BufferedReader(arq);
		    String linha = lerArq.readLine(); 
		      
		    while (linha != null) {
		    	String str[] = linha.split("\\|");
		    	ENTITY ent = (ENTITY) getEntity().getInstanceFromArray(str);
		    	if (ent == null) {
		    		return getEntities();
		    	}
		    	getEntities().add(ent);
		    	getProgress().getLabel().setText("Importando o registro " +getEntities().size()  +" de " +getSizeFile() +" no total.");
		    	getProgress().getProgress().setValue(getEntities().size());
		    	if (getTime() > 0)
		    		Thread.currentThread().sleep(getTime());
		    	linha = lerArq.readLine(); 
		    }
			arq.close();
			
			Path path = new Path();
            path.setProperties(getPath(), getPathFile().toString());
		
		} catch (IOException e) {
			System.err.printf("Erro na abertura do arquivo: %s.\n",
		    e.getMessage());
		}
		return getEntities();
	}
	
	public GenericImportFile getgImportFile() {
		return gImportFile;
	}
	public void setgImportFile(GenericImportFile gImportFile) {
		this.gImportFile = gImportFile;
	}
	public ENTITY getEntity() {
		return entity;
	}
	public void setEntity(ENTITY entity) {
		this.entity = entity;
	}
	
	public ArrayList<ENTITY> getEntities() {
		if (entities == null) {
			entities = new ArrayList<ENTITY>();
		}
		return entities;
	}

	public void setEntities(ArrayList<ENTITY> entities) {
		this.entities = entities;
	}
	
	public JProgressBarForm getProgress() {
		return progress;
	}

	public void setProgress(JProgressBarForm progress) {
		this.progress = progress;
	}
}